#include <math.h>
#include "user.h"
#include "user_doe.h"

static double r, f1, f2, wl, s;
static int sign;

double BifocalLensFun(double rr) {
double  fd1, fd2, ph;

fd1=2*f1*f2/(f1+f2);
fd2=2*f1*f2/(f2-f1);

   ph=fmod(M_PI*rr*rr/(fd2*wl),2*M_PI);
   ph=(ph>M_PI)?M_PI:0;
   if(sign) return(ph);
   else     return(ph-M_PI*rr*rr/(fd1*wl));

}
void BifocalLensMinMax(double *min, double *max) {
double fd2=2*f1*f2/(f2-f1);

   if(sign) {  *min=0; *max=M_PI;  }
   else {
      int i=r*r/(wl*fd2);
      double rr = BifocalLensFun(sqrt(i*wl*fd2));
      *min = BifocalLensFun(r);
      if( *min>rr ) *min = rr;
      *max= BifocalLensFun( sqrt(wl*fd2) );
      if( *max<0 ) *max=0;
   }
}
void BifocalLens()   {
   char *ParNames[]={  "Aperure  Radius    :",
		       "Focus_1            :",
		       "Focus_2            :",
		       "WaveLength (micron):",
		       "Discretization Step:",
		       "With Lens/Else  0/1:"
		 };
   char *Default[]={"5           ",
                    "200         ",
                    "220         ",
		    ".63         ",
                    ".005       ",
                    "1          "};
   char *InputValues[6];
   char *Title={"Bifocal Lens"};
   if(!sedit(25,5,6,ParNames,InputValues,Default,Title))  return ;

   // read input data
   sscanf(InputValues[0],"%lf",&r);   sprintf(Default[0],"%f",r);
   sscanf(InputValues[1],"%lf",&f1);  sprintf(Default[1],"%f",f1);
   sscanf(InputValues[2],"%lf",&f2);  sprintf(Default[2],"%f",f2);
   sscanf(InputValues[3],"%lf",&wl);  sprintf(Default[3],"%f",wl);
   sscanf(InputValues[4],"%lf",&s);   sprintf(Default[4],"%f",s);
   sscanf(InputValues[5],"%d",&sign); sprintf(Default[5],"%d",sign);
   wl=wl/1000;

   double min, max;
   BifocalLensMinMax(&min, &max);
   AnnularDOE(Phase, max, min, BifocalLensFun);

   UndoMenu(2) ;
   if(MessageSize(2*r, 2*r, s)) return;
   MessageName(Title);    // write title
   for(int i=0; i<6; i++)
      MessageParam(i+1,"%s %s",ParNames[i],Default[i]);
   MessageOut();               // output all string to InfoWindow

   return;
}
